package com.ruoyi.web.controller.app;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.BodyInfoVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ITLeachRecordsService;
import com.ruoyi.system.utils.CloakUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("/link")
public class OpenController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(OpenController.class);

    @Autowired
    private TWorkOrderMapper tWorkOrderMapper;
    @Autowired
    private TWorkOrderItemMapper tWorkOrderItemMapper;
    @Autowired
    private TAccessRecordsMapper tAccessRecordsMapper;
    @Autowired
    private TEfficAccessRecordsMapper tEfficAccessRecordsMapper;
    @Autowired
    private TLeachRecordsMapper tLeachRecordsMapper;

    @GetMapping("/{id}")
    public void link(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("工单ID为：{}",id);
        String ip = IpUtils.getIpAddr(request);
        //添加点击数
        TAccessRecords tAccessRecords = new TAccessRecords();
        tAccessRecords.setWorkOrderId(id);
        tAccessRecords.setIp(ip);
        tAccessRecords.setCreateTime(new Date());
        tAccessRecordsMapper.insertTAccessRecords(tAccessRecords);
        TWorkOrder tWorkOrder = tWorkOrderMapper.selectTWorkOrderById(id);
        TWorkOrderItem item = new TWorkOrderItem();
        item.setStatus(1);
        item.setWorkOrderId(id);
        List<TWorkOrderItem> tWorkOrderItems = tWorkOrderItemMapper.selectTWorkOrderItemList(item);
        if (tWorkOrderItems.isEmpty()){
            response.sendRedirect(checkDom(tWorkOrder.getSafeUrl()));
        }else {
            if (tWorkOrder.getCloakStatus() == 1) {
                //走接口记录
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", "20221017_EhV204as5");
                jsonObject.put("ip", IpUtils.getIpAddr(request));
                jsonObject.put("domain", request.getRequestURI());
                jsonObject.put("country_code", tWorkOrder.getSupport());
                System.err.println(request.getHeaders("referer"));
                jsonObject.put("referer", request.getHeader("referer"));
                Enumeration<String> enumeration = request.getHeaderNames();
                JSONObject head = new JSONObject();
                JSONObject ck = new JSONObject();
                while (enumeration.hasMoreElements()) {
                    String name = enumeration.nextElement();
                    String value = request.getHeader(name);
                    head.put(name,value);
                }
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        ck.put(cookie.getName(), cookie.getValue());
                    }
                }
                jsonObject.put("headers",JSONObject.toJSONString(head) );
                jsonObject.put("cookies",JSONObject.toJSONString(ck) );
                System.err.println(jsonObject);
                String s = post(JSONObject.toJSONString(jsonObject));
                System.err.println("请求结果：" + s);
                JSONObject json = JSONObject.parseObject(s);
                TLeachRecords tLeachRecords = new TLeachRecords();
                tLeachRecords.setWorkOrderId(id);
                tLeachRecords.setBody(JSONObject.toJSONString(jsonObject));
                tLeachRecords.setIp(ip);
                tLeachRecords.setAdopt(json.getBoolean("result") ? 1 : 0);
                tLeachRecords.setResult(s);
                tLeachRecords.setCreateTime(new Date());
                tLeachRecords.setCookies(JSONObject.toJSONString(ck));
                tLeachRecords.setHeaders(JSONObject.toJSONString(head));
                tLeachRecords.setRealIp(request.getHeader("x-real-ip"));
                tLeachRecords.setAccept(request.getHeader("accept"));
                tLeachRecords.setAcceptLua(request.getHeader("accept-language"));
                tLeachRecords.setAgent(request.getHeader("user-agent"));
                try {
                    if (json.getBoolean("result")) {
                        //添加有效点击
                        TEfficAccessRecords tEfficAccessRecords = new TEfficAccessRecords();
                        tEfficAccessRecords.setWorkOrderId(id);
                        tEfficAccessRecords.setIp(ip);
                        tEfficAccessRecords.setContent(JSONObject.toJSONString(jsonObject));
                        tEfficAccessRecords.setCreateTime(new Date());
                        tEfficAccessRecordsMapper.insertTEfficAccessRecords(tEfficAccessRecords);
                        tLeachRecordsMapper.insertTLeachRecords(tLeachRecords);
                        response.sendRedirect(checkDom(tWorkOrderItems.get(0).getPhone()));
                    } else {
                        tLeachRecordsMapper.insertTLeachRecords(tLeachRecords);
                        response.sendRedirect(checkDom(tWorkOrder.getSafeUrl()));
                    }
                }catch (Exception e){
                    TEfficAccessRecords tEfficAccessRecords = new TEfficAccessRecords();
                    tEfficAccessRecords.setWorkOrderId(id);
                    tEfficAccessRecords.setIp(ip);
                    tEfficAccessRecords.setContent(JSONObject.toJSONString(jsonObject));
                    tEfficAccessRecords.setCreateTime(new Date());
                    tEfficAccessRecordsMapper.insertTEfficAccessRecords(tEfficAccessRecords);
                    tLeachRecordsMapper.insertTLeachRecords(tLeachRecords);
                    response.sendRedirect(checkDom(tWorkOrderItems.get(0).getPhone()));

                }
            }else {
                response.sendRedirect(checkDom(tWorkOrderItems.get(0).getPhone()));
            }
        }
    }

    @Autowired
    private ITLeachRecordsService tLeachRecordsService;

    @GetMapping("/task")
    public AjaxResult task(){
        List<TLeachRecords> list = tLeachRecordsService.selectTLeachRecordsList(new TLeachRecords());
        for (TLeachRecords tLeachRecords : list) {
            BodyInfoVo bodyInfoVo = JSONObject.parseObject(tLeachRecords.getBody(),BodyInfoVo.class);
            System.err.println(bodyInfoVo);
            System.err.println(bodyInfoVo.getHeaders());
            System.err.println(bodyInfoVo.getCookies());
            tLeachRecords.setCookies(bodyInfoVo.getCookies());
            tLeachRecords.setHeaders(bodyInfoVo.getHeaders());
            tLeachRecords.setRealIp(JSONObject.parseObject(bodyInfoVo.getHeaders()).getString("x-real-ip"));
            tLeachRecords.setAccept(JSONObject.parseObject(bodyInfoVo.getHeaders()).getString("accept"));
            tLeachRecords.setAcceptLua(JSONObject.parseObject(bodyInfoVo.getHeaders()).getString("accept-language"));
            tLeachRecords.setAgent(JSONObject.parseObject(bodyInfoVo.getHeaders()).getString("user-agent"));
            tLeachRecordsService.updateTLeachRecords(tLeachRecords);
        }
        return AjaxResult.success();
    }

    @GetMapping("/leach")
    public TableDataInfo leach(TLeachRecords tLeachRecords)
    {
        startPage();
        List<TLeachRecords> list = tLeachRecordsService.selectTLeachRecordsList(tLeachRecords);
        return getDataTable(list);
    }

    /**
     * 判断是否存在http或者https
     */
    public static String checkDom(String url){
        return url.matches("^https?://.*$") ? url : "http://" + url;
    }
    /**
     * 获取客户端headers信息
     * @param request 请求
     * @return 结果
     */
    private static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> headerMap = new HashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            System.err.println(name);
            String value = request.getHeader(name);
            headerMap.put(name, value);
        }
        return headerMap;
    }

    private static final String API_URL = "http://www.tiktokba.com/cloak/byApi";
    private static final String ESCLOAK_KEY = "PlJm4UAYsHRcMXBExWdSTza9fkFgojqQ";
    /**
     * 发送 post 请求
     *
     * @param jsonStr Form表单json字符串
     * @return 请求结果
     */
    public static String post(String jsonStr) {
        // 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建post请求方式实例
        HttpPost httpPost = new HttpPost(API_URL);

        // 设置请求头 发送的是json数据格式
        httpPost.setHeader("Content-type", "application/json;");
        httpPost.setHeader("escloak-key",ESCLOAK_KEY);

        // 设置参数---设置消息实体 也就是携带的数据
        StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
        // 设置编码格式
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        // 把请求消息实体塞进去
        httpPost.setEntity(entity);

        // 执行http的post请求
        CloseableHttpResponse httpResponse;
        String result = null;
        try {
            httpResponse = httpClient.execute(httpPost);
            result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

}
